import Request, { type HttpMethod, type HttpRequestConfig } from 'luch-request'

//
const service = new Request({
  baseURL: 'https://consult-api.itheima.net',
  timeout: 10 * 1000,
  custom: {
    loading: true,
  },
})
// 接口白名单
const whiteList = ['/code', '/login', '/login/password']

// 请求拦截器
service.interceptors.response.use(
  (res) => {
    
    if (res.data.code !== 10000) {
      uni.showToast({
        title: res.data.message,
        icon: 'none',
      })
      return Promise.reject(res.data)
    }
    
    return res.data.data
  },
  (err) => {
    if (err.data.code === 401) {
      uni.showToast({
        title: err.data.message,
        icon: 'none',
      })
    }
    return Promise.reject(err)
  }
)

export interface LoginData {
  /**
   * 用户名
   */
  account?: string
  /**
   * 头像
   */
  avatar?: string
  /**
   * 用户id
   */
  id?: string
  /**
   * 脱敏手机号，带星号的手机号
   */
  mobile?: string
  /**
   * refreshToken
   */
  refreshToken: string
  /**
   * token
   */
  token: string
}

interface ServiceResponse<T> {
  code: number
  message: string
  data: T
}
// 封装请求工具
const request = <T>(
  url: string,
  method: HttpMethod = 'GET',
  submitData?: object,
  config?: HttpRequestConfig
) => {
  return service.request<T, ServiceResponse<T>>({
    url: url,
    method: method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData,
    ...config,
  })
}

export { service, request }
